function isJson(obj) {
    return typeof(obj) === "object" && Object.prototype.toString.call(obj).toLowerCase() === "[object object]" && !obj.length;
}
$(function () {
    $(document).on('afterValidateAttribute', 'form', function (event, attribute, message) {
        var $form = $(this);
        var $error = $form.find(attribute.container).find(attribute.error);
        var px = message.length > 0 ? '-10px' : 0;
        $error.css('margin-bottom', px);
        return false;
    });

    $(document).on('beforeSubmit', 'form', function () {
        var $form = $(this);
        if ($form.find('.has-error').length) {
            return false;
        }
        $('.login-error').hide();

        var $btn = $form.find('.btn');
        $btn.attr('disabled', 'disabled').addClass('disabled');

        $.ajax({
            type: 'POST',
            url: $form.prop('action'),
            data: $form.serialize(),
            dataType: 'json',
            success: function (res) {
                window.setTimeout(function () {
                    if (isJson(res) && res.code === 0) {
                        window.location.href = res['data']['redirect'];
                        return false;
                    }
                    $('.login-error').fadeIn().html(res['msg']);
                    $btn.removeClass('disabled').removeAttr('disabled');

                    window.setTimeout(function () {
                        $('.login-error').fadeOut();
                    }, 3000);
                }, 1500);
            },
            error: function () {
                $('.login-error').fadeIn();
                $btn.removeClass('disabled').removeAttr('disabled');
                window.setTimeout(function () {
                    $('.login-error').fadeOut();
                }, 2500);
            }
        });
        return false;
    });
});